import React, { PureComponent } from 'react';
import { Table, Input, InputNumber, Popconfirm, Form, Button, Card, Select } from 'antd';
import { withRouter } from 'react-router';

const { Option } = Select

const EditableContext = React.createContext();
class EditableCell extends React.Component {

    getInput = () => {
        if (this.props.type == 'number') {
            return <InputNumber placeholder='请输入' style={{ width: '100%' }} />;
        }
        if (this.props.type == 'check') {
            return <Select placeholder='请选择' style={{ width: '100%' }}>
                <Option value={1}>label1</Option>
                <Option value={2}>label2</Option>
                <Option value={3}>label3</Option>
            </Select>;
        }
        return <Input placeholder='请输入' style={{ width: '100%' }} />;
    };

    renderCell = ({ getFieldDecorator }) => {
        const {
            editing,
            dataIndex,
            title,
            record,
            index,
            children,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item style={{ margin: 0 }}>
                        {getFieldDecorator(dataIndex + '_' + record.batchNo, {
                            initialValue: record[dataIndex],
                        })(this.getInput())}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };

    render() {
        return <EditableContext.Consumer >{this.renderCell}</EditableContext.Consumer>;
    }
}

const EditTable = ({ form, dataSource, isEdit, columns, titleStyle, title, rowKey }) => {

    const components = {
        body: {
            cell: EditableCell,
        },
    };
    const Columns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: record => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEdit,
                type: col.type
            }),
        };
    });
    return (
        <Card title={<div style={titleStyle}>{title}</div>} bordered={false}>
            <EditableContext.Provider value={form}>
                <Table
                    components={components}
                    rowKey={rowKey}
                    bordered
                    dataSource={dataSource}
                    columns={Columns}
                    rowClassName="editable-row"
                    pagination={false}
                />
            </EditableContext.Provider>
        </Card>
    );
};

export default Form.create()(EditTable);